package me.zingon.WebSocket.tools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Created by ZTC on 12/21/2016.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class TalkService {

    @Autowired
    ThreadPoolTaskExecutor taskExecutor;

    private Map<String,String> NameMap=new ConcurrentHashMap<String,String>();

    private Map<String,WebSocketSession> SessionMap=new ConcurrentHashMap<String,WebSocketSession>();

    private Queue<String> MsgQueue=new ConcurrentLinkedQueue<String>();

    public String getName(String sessionId){
        return NameMap.get(sessionId);
    }

    public void saveTalker(String name,String reqId,WebSocketSession ws){
        NameMap.put(reqId,name);
        SessionMap.put(reqId,ws);
    }

    public void rmTalker(String reqId){
        NameMap.remove(reqId);
        SessionMap.remove(reqId);
    }



    public void send2All(final String msg){
        taskExecutor.execute(new Runnable() {
            public void run() {
                Set<Map.Entry<String, WebSocketSession>> set=SessionMap.entrySet();
                for(Map.Entry<String,WebSocketSession> s:set){
                    if(s.getValue().isOpen())
                        try {
                            s.getValue().sendMessage(new TextMessage(msg));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                }
            }
        });
    }
}
